package com.cn.xiaonuo.slbfinances.shopassets.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cn.xiaonuo.common.constant.Status;
import com.cn.xiaonuo.common.entity.BusinessMessage;
import com.cn.xiaonuo.common.utils.ExportExcelUtils;
import com.cn.xiaonuo.common.utils.pageutil.PageUtil;
import com.cn.xiaonuo.common.vo.ExcelData;
import com.cn.xiaonuo.dbs.core.annotation.DataSource;
import com.cn.xiaonuo.slbfinances.shopassets.entity.SlRevenueDetails;
import com.cn.xiaonuo.slbfinances.shopassets.entity.SlbShop;
import com.cn.xiaonuo.slbfinances.shopassets.mapper.SlRevenueDetailsMapper;
import com.cn.xiaonuo.slbfinances.shopassets.mapper.SlShopMapper;
import com.cn.xiaonuo.slbfinances.shopassets.param.PageRevenueDetailsParam;
import com.cn.xiaonuo.slbfinances.shopassets.rsp.RevenueDetailsRsp;
import com.cn.xiaonuo.slbfinances.shopassets.service.SlRevenueDetailsService;
import com.cn.xiaonuo.slbfinances.slborders.entity.SlShopPayment;
import com.cn.xiaonuo.slbfinances.slborders.mapper.SlShopPaymentMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @BelongsProject: slb-reports-java
 * @Author: likui
 * @CreateTime: 2022-12-21  17:28
 * @Description: TODO
 */
@Service
@Slf4j
public class SlRevenueDetailsServiceImpl implements SlRevenueDetailsService {

    @Autowired
    private SlShopMapper slShopMapper;
    @Autowired
    private SlRevenueDetailsMapper slRevenueDetailsMapper;
    @Autowired
    private SlShopPaymentMapper slShopPaymentMapper;
    /**
     * 分页查询最大条数
     */
    private static final int MAX_PAGE_SIZE = 500;

    @Transactional(rollbackFor = Exception.class)
    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage revenueDetails() {
        BusinessMessage message = new BusinessMessage();
        log.info("定时同步收入明细任务执行开始!");
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);
        String createTime = fmt.format(calendar.getTime());
        PageUtil pageUtil = new PageUtil();
        pageUtil.setPageSize(MAX_PAGE_SIZE);
        PageInfo<SlShopPayment> slShopPaymentPageInfo;
        try {
            int count=0;
            do {
                PageHelper.startPage(pageUtil.getPageNo(),pageUtil.getPageSize());
                List<SlShopPayment> slShopPayments = slShopPaymentMapper.selectNormal(createTime);
                slShopPaymentPageInfo = new PageInfo<>(slShopPayments);
                for (SlShopPayment slShopPayment : slShopPaymentPageInfo.getList()) {
                    SlRevenueDetails slRevenueDetails = new SlRevenueDetails();
                    slRevenueDetails.setOrderId(slShopPayment.getOrderId());
                    slRevenueDetails.setSerialNumber(slShopPayment.getSerialNumber());
                    slRevenueDetails.setTransactionTime(Convert.toDate(slShopPayment.getCreateTime()));
                    slRevenueDetails.setIsPubGoods(slShopPayment.getOrderType());
                    slRevenueDetails.setPayType(slShopPayment.getPayType());
                    slRevenueDetails.setTotalAmount(slShopPayment.getOrderPrice());
                    slRevenueDetails.setServiceCharge(slShopPayment.getCommission());
                    slRevenueDetails.setRevenueAmount(slShopPayment.getActualPrice());
                    slRevenueDetails.setTotalCash(slShopPayment.getPaFzMoney());
                    slRevenueDetails.setTotalGwjSy(slShopPayment.getTotalHpcGwj());
                    slRevenueDetails.setTotalGzGwj(slShopPayment.getTotalGzGwj());
                    slRevenueDetails.setGwqIncome(slShopPayment.getGwjFzMoney());
                    slRevenueDetails.setCashPayment(slShopPayment.getTotalAmount());
                    SlbShop slbShop = slShopMapper.selectById(slShopPayment.getShopId());
                    slRevenueDetails.setShopId(slbShop.getId());
                    slRevenueDetails.setShopName(slbShop.getName());
                    slRevenueDetails.setSlShopType(slbShop.getSlShopType());
                    slRevenueDetails.setUserId(slbShop.getOwnerId());
                    slRevenueDetailsMapper.insert(slRevenueDetails);
                    count+=1;
                }
                pageUtil.setPageNo(pageUtil.getPageNo()+1);
            }while (slShopPaymentPageInfo.isHasNextPage());
            log.info("定时同步收入明细任务执行成功[{}]条,工{}页",count,pageUtil.getPageNo()-1);
            message.setMessage(Status.success);
            message.setCode(Status.successCode);
            message.setSuccess(true);
        } catch (Exception e) {
            log.error("定时同步收入明细任务执行失败，原因{}", e.getMessage());
            message.setCode(Status.failCode);
            message.setSuccess(false);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return message;
    }

    public QueryWrapper<SlRevenueDetails> queryWrapper(PageRevenueDetailsParam param) {
        QueryWrapper<SlRevenueDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
        if (ObjectUtils.isNotEmpty(param.getSerialNumber())) {
            queryWrapper.eq("serial_number", param.getSerialNumber());
        }
        if (ObjectUtils.isNotEmpty(param.getIsPubGoods())) {
            queryWrapper.eq("is_pub_goods", param.getIsPubGoods());
        }
        if (ObjectUtils.isNotEmpty(param.getUserId())) {
            queryWrapper.eq("user_id", param.getUserId());
        }
        if (ObjectUtils.isNotEmpty(param.getSlShopType())) {
            queryWrapper.eq("sl_shop_type", param.getSlShopType());
        }
        if (ObjectUtils.isNotEmpty(param.getPayType())) {
            queryWrapper.eq("pay_type", param.getPayType());
        }
        if (ObjectUtils.isNotEmpty(param.getCreatedBeginTime()) && ObjectUtils.isNotEmpty(param.getCreatedEndTime())) {
            queryWrapper.ge("transaction_time", param.getCreatedBeginTime());
            queryWrapper.le("transaction_time", param.getCreatedEndTime());
        }
        queryWrapper.orderByDesc("id");
        return queryWrapper;
    }

    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage pageRevenueDetails(PageRevenueDetailsParam param) {
        BusinessMessage message = new BusinessMessage();
        RevenueDetailsRsp rsp = new RevenueDetailsRsp();
        QueryWrapper<SlRevenueDetails> queryWrapper = this.queryWrapper(param);
        Page<SlRevenueDetails> selectPage = slRevenueDetailsMapper.selectPage(new Page<>(param.getPageNo(), param.getPageSize()), queryWrapper);
        rsp.setSelectPage(selectPage);
        RevenueDetailsRsp sumAmount = slRevenueDetailsMapper.sumAmount(param);
        rsp.setSumTotalAmount(sumAmount.getSumTotalAmount());
        rsp.setSumIncomeFromPoints(sumAmount.getSumIncomeFromPoints());
        rsp.setSumTotalIncome(sumAmount.getSumTotalIncome());
        rsp.setSumTotalServiceCharge(sumAmount.getSumTotalServiceCharge());
        RevenueDetailsRsp sumWechatRevenue = slRevenueDetailsMapper.sumWechatRevenue(param);
        rsp.setSumWechatRevenue(sumWechatRevenue.getSumWechatRevenue());
        RevenueDetailsRsp sumAlipayRevenue = slRevenueDetailsMapper.sumAlipayRevenue(param);
        rsp.setSumAlipayRevenue(sumAlipayRevenue.getSumAlipayRevenue());
        message.setData(rsp);
        message.setMessage(Status.success);
        message.setSuccess(true);
        message.setCode(Status.successCode);
        return message;
    }

    @Override
    @DataSource(name = "jyb_soole_data_hn")
    public void revenueDetailsExcel(HttpServletResponse response, PageRevenueDetailsParam param) {
        SimpleDateFormat ymdhms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        QueryWrapper<SlRevenueDetails> queryWrapper = this.queryWrapper(param);
        List<SlRevenueDetails> slRevenueDetails = slRevenueDetailsMapper.selectList(queryWrapper);
        RevenueDetailsRsp sumAmount = slRevenueDetailsMapper.sumAmount(param);
        RevenueDetailsRsp sumWechatRevenue = slRevenueDetailsMapper.sumWechatRevenue(param);
        RevenueDetailsRsp sumAlipayRevenue = slRevenueDetailsMapper.sumAlipayRevenue(param);
        try {
            List<List<Object>> rows = new ArrayList();
            ExcelData data = new ExcelData();
            //sheet表名称
            data.setName("商家收入明细导出");
            List<String> firstTitles = new ArrayList<>();
            firstTitles.add("订单交易金额汇总");
            firstTitles.add(Convert.toStr(sumAmount.getSumTotalAmount()));
            firstTitles.add("合计收入金额汇总");
            firstTitles.add(Convert.toStr(sumAmount.getSumTotalIncome()));
            firstTitles.add("积分收入汇总");
            firstTitles.add(Convert.toStr(sumAmount.getSumIncomeFromPoints()));
            firstTitles.add("支付宝收入汇总");
            firstTitles.add(Convert.toStr(sumAlipayRevenue.getSumAlipayRevenue()));
            firstTitles.add("微信收入汇总");
            firstTitles.add(Convert.toStr(sumWechatRevenue.getSumWechatRevenue()));
            firstTitles.add("平台服务费收入汇总");
            firstTitles.add(Convert.toStr(sumAmount.getSumTotalServiceCharge()));
            data.setTitles(firstTitles);
            //表头
            List<Object> titles = new ArrayList();
            titles.add("店铺名称");
            titles.add("订单编号");
            titles.add("交易时间");
            titles.add("商家类型");
            titles.add("订单来源");
            titles.add("商家用户ID");
            titles.add("收/付款方式");
            titles.add("订单交易金额");
            titles.add("服务费(7%)");
            titles.add("收入金额");
            rows.add(titles);
            for (SlRevenueDetails details : slRevenueDetails) {
                List<Object> row1 = new ArrayList();
                row1.add(details.getShopName());
                row1.add(details.getSerialNumber());
                String format = ymdhms.format(details.getTransactionTime());
                row1.add(format);
                if (ObjectUtils.isNotEmpty(details.getSlShopType())) {
                    if (details.getSlShopType().equals(0)) {
                        row1.add("普通店铺");
                    } else if (details.getSlShopType().equals(1)) {
                        row1.add("普通加盟店铺");
                    } else if (details.getSlShopType().equals(2)) {
                        row1.add("运营中心店铺");
                    } else if (details.getSlShopType().equals(3)) {
                        row1.add("厂家店铺");
                    }
                }
                if (details.getIsPubGoods().equals(2)) {
                    row1.add("普通商品");
                } else if (details.getIsPubGoods().equals(1)) {
                    row1.add("一县一品商品");
                }
                row1.add(details.getUserId());
                if (details.getPayType().equals(1)) {
                    row1.add("微信");
                } else if (details.getPayType().equals(2)) {
                    row1.add("支付宝");
                } else if (details.getPayType().equals(5)) {
                    row1.add("线下付款");
                } else if (details.getPayType().equals(10)) {
                    row1.add("购物劵");
                } else if (details.getPayType().equals(11)) {
                    row1.add("支付宝+购物劵");
                }else if (details.getPayType().equals(12)) {
                    row1.add("微信+购物劵");
                }else if (details.getPayType().equals(15)) {
                    row1.add("微信+线下支付");
                }else if (details.getPayType().equals(16)) {
                    row1.add("支付宝+线下支付");
                }else if (details.getPayType().equals(17)) {
                    row1.add("银联");
                }else if (details.getPayType().equals(18)) {
                    row1.add("银联+购物券");
                }else if (details.getPayType().equals(101)) {
                    row1.add("好收银支付宝");
                }else if (details.getPayType().equals(102)) {
                    row1.add("好收银微信");
                }else if (details.getPayType().equals(103)) {
                    row1.add("好收银云闪付");
                }else {
                    row1.add("其他");
                }
                row1.add(details.getTotalAmount());
                row1.add(details.getServiceCharge());
                row1.add(details.getRevenueAmount());
                rows.add(row1);
            }
            data.setRows(rows);
            ExportExcelUtils.exportExcel(response, "商家收入明细记录导出.xlsx", data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
